package web_programing.review.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @author haomin
 * @date 2022/09/26 09:57
 **/
public class Server {
    // 1. 可以写在文件中
    // 2. 可以写在数据库中
    private static final HashMap<String, String> map = new HashMap<>();
    static {
        map.put("apple", "苹果");
        map.put("banana", "香蕉");
    }

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8080);
        while(true){
            // 1. 读取请求
            byte[] buf = new byte[1024];
            DatagramPacket received = new DatagramPacket(buf, buf.length);
            socket.receive(received); // 服务器会阻塞在这

            // 2. 处理
            InetAddress address = received.getAddress(); // 获得ip
            int port = received.getPort();               // 获得端口
            int n = received.getLength();                // 真正收到的数据长度
            byte[] actualData = Arrays.copyOf(buf, n);   // 真正有用的数据
            // byte[] + 字符集编码 -> String
            String request = new String(actualData, 0, actualData.length, "utf-8");

            // 3. 分析请求
            if(!request.startsWith("请求格式头\r\n") && !request.startsWith("请求格式尾\r\n")){
                continue; // 不符合应用层的请求协议，不做处理
            }
            String englishWord = request.substring("请求格式头\r\n".length(), request.length() - "请求格式尾\r\n".length());
            Log.println(englishWord);
            String chineseWord = map.getOrDefault(englishWord, "不认识");

            // 4. 发送响应
            String response = String.format("收到，响应为\r\n%s\r\n", chineseWord);
            // String + 字符集编码 -> byte[]
            byte[] bytes = response.getBytes("utf-8");
            DatagramPacket sent = new DatagramPacket(
                    bytes, 0, bytes.length,
                    address,
                    port
            );
            socket.send(sent);
            Log.println("响应成功"+response);
        }
    }
}